//
//  ConfirmView.swift
//  funcode
//
//  Created by Wan Jiading on 2016/11/11.
//  Copyright © 2016年 WanJiading. All rights reserved.
//

import UIKit

class ConfirmView: UIView {

	var maskButton: UIButton!
	var backgroundView: UIView!
	var titleLabel: UILabel!
	
	let backgroundViewWidth: CGFloat = 300
	
	convenience init(_ title: String) {
		self.init()
		
		backgroundView = UIView()
		backgroundView.frame = CGRect(x: 0, y: 0, width: backgroundViewWidth, height: 200)
		backgroundView.backgroundColor = UIColor.white
		backgroundView.layer.cornerRadius = 10
		
		titleLabel = UILabel()
		titleLabel.text = title
		titleLabel.textAlignment = NSTextAlignment.center
		titleLabel.sizeToFit()
		backgroundView.addSubview(titleLabel)
		titleLabel.frame = CGRect(x: 0, y: 20, width: backgroundView.frame.width, height: titleLabel.frame.height)
		
		maskButton = UIButton(type: UIButtonType.custom)
		maskButton.frame = UIScreen.main.bounds
		maskButton.addSubview(backgroundView)
		maskButton.addTarget(self, action: #selector(dismissSelf), for: UIControlEvents.touchUpInside)
		
		maskButton.isUserInteractionEnabled = true
		self.frame = maskButton.bounds
		self.isUserInteractionEnabled = true
		self.addSubview(maskButton)
	}
	
	override func layoutSubviews() {
		super.layoutSubviews()
		
		let size = UIScreen.main.bounds
		let x = (size.width - backgroundViewWidth) * 0.5
		backgroundView.frame.origin.x = x
		
		let y = (size.height - backgroundView.frame.height) * 0.5
		backgroundView.frame.origin.y = y
	}
	
	func show() {
		layoutSubviews()
		
		let animation = CAKeyframeAnimation(keyPath: "transform")
		animation.duration = 0.25
		
		let values = [
			NSValue.init(caTransform3D: CATransform3DMakeScale(0.8, 0.8, 1.0)),
			NSValue.init(caTransform3D: CATransform3DMakeScale(1.01, 1.01, 1.0)),
			NSValue.init(caTransform3D: CATransform3DMakeScale(0.99, 0.99, 1.0)),
			NSValue.init(caTransform3D: CATransform3DMakeScale(1.0, 1.0, 1.0)),
			]
		animation.values = values
		backgroundView.layer.add(animation, forKey: nil)
		
		maskButton.backgroundColor = UIColor.rgb("000000", alpha: 0.5)
		UIApplication.shared.keyWindow?.addSubview(self)
	}
	
	func dismissSelf() {
		
		let animation = CAKeyframeAnimation(keyPath: "transform")
		animation.duration = 0.25
		let values = [
			NSValue.init(caTransform3D: CATransform3DMakeScale(1.0, 1.0, 1.0)),
			NSValue.init(caTransform3D: CATransform3DMakeScale(0.8, 0.8, 1.0)),
			NSValue.init(caTransform3D: CATransform3DMakeScale(0.1, 0.1, 1.0)),
			]
		animation.values = values
		backgroundView.layer.add(animation, forKey: nil)
		
		UIView.animate(withDuration: 0.25, delay: 0, options: UIViewAnimationOptions.curveEaseOut, animations: { [unowned self] in
			self.maskButton.alpha = 0
		}, completion:{ [unowned self] (finished) in
			self.removeFromSuperview()
		})
	}
	
	deinit {
		DebugLogFunc()
	}

}
